package test;

import java.util.HashSet;

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;

import lights.adapters.Field;
import lights.dracots.Tuple;
import lights.interfaces.ITuple;
import lime2.Location;
import lime2.TupleID;
import sagroup.dracots.DracoTS;
import sagroup.dracots.DracoTuple;
import sagroup.dracots.FlatShareTuple;
import sagroup.dracots.ShareTuple;
import sagroup.dracots.TupleType;

public class UpdateAgent implements Runnable {
	public void run() {
		DracoTS dts = DracoTS.get("testing");
		HashSet<TupleID> tuples = new HashSet<TupleID>();
		
		// out a set of local tuples
		for (int i = 1; i < 10; i++) {
			ITuple it = new Tuple();
			it.add(new Field().setValue("Hello" + i));
			DracoTuple ret = dts.out(new FlatShareTuple(new TupleType("type"),
					it));
			if (ret != null) {
				tuples.add(ret.getVID());
				System.out.println("OutAgent has out tuple with vid: "
						+ ret.getVID());
			}
		}
		
		RandomData randomData = new RandomDataImpl();
		DracoTuple orig = ShareTuple.createVIDTemplate((TupleID)randomData.nextSample(tuples, 1)[0]);
		ShareTuple ret = (ShareTuple) dts.rd(orig);
		if( ret != null){
			System.out.println("UpdateAgent has read tuple with vid: "	+ ret.getVID() + " and version: " + ret.getVer());
		}

		ShareTuple template = ShareTuple.createVIDTemplate(ret.getVID());
		template.setReplica(false);
		template.setCurr(Location.HERE);
		template.setDest(Location.HERE);

		ShareTuple newTuple = new FlatShareTuple(new TupleType("type"),(new Tuple()).add(new Field().setValue("World")));
		ShareTuple ret1 = (ShareTuple) dts.update(template, newTuple);
		ret1 = (ShareTuple) dts.rd(template);
		if (ret1 != null) {
			System.out.println("UpdateAgent has update tuple to one with vid: "	+ ret1.getVID() + " and version: " + ret1.getVer());
		}
		System.out.println("UpdateAgent finished!");
	}
}
